<?php
namespace app\api\controller;

use app\api\controller\Chatupload;
use app\common\model\Csuser as CsuserModel;
use app\common\model\Users as UsersModel;
use app\common\model\WxUser as WxUserModel;
use app\common\model\AuthorWxUser as AuthorWxUserModel;
use app\common\util\WechatThirdUtil;
use think\Db;

class User extends Base {

    private $author_wx_user_model;
    private $csuser_model;
    private $users_model;
    private $wx_user;
    private $config;

    public function _initialize() {
        $this->csuser_model = new CsuserModel();
        $this->author_wx_user_model = new AuthorWxUserModel();
        $this->users_model = new UsersModel();
        $this->wx_user = new WxUserModel();
        $this->config = $this->wx_user->find();
    }

    /**
     * 向用户发送文本信息
     * @param appid 公众号appid
     * @param openid 用户openid
     * @param content 发送内容
     * @param cs_id 客服id
     * @param type 内容类型
     * @param send_time 发送时间
     * @param customerService 指定客服账号
     */
    public function sendMsgForUser(){
            $data = $this->request->post();
            $appid = $data['appid'];
            $openid = $data['openid'];
            $content = $data['content'];
            $customerService = isset($data['customerService']) ? $data['customerService'] : '';
            $author_wx = $this->author_wx_user_model->where('appid',$appid)->where('authorized',1)->find();
            $wechatObj = new WechatThirdUtil($this->config , $author_wx);
            if(!empty($customerService)){
                $result = $wechatObj->appointSendMsgToOne($openid,$content,$customerService);
            }else{
                $result = $wechatObj->sendMsgToOne($openid,$content);
            }
            if($result){
                $pid = $this->csuser_model->where('id',$data['cs_id'])->value('pid');
                $post_arr = [
                    'type'    => $data['type'],
                    'content' => $content, //消息文本
                    'openid'  => $openid, //用户openid
                    'appid'   => $appid, //对应公众号appid
                    'cs_id'   => $data['cs_id'], //客服id
                    'send_time' => $data['send_time'], //发送时间
                    'send_type' => '1002',
                    'pid' => $pid == 0 ? $data['cs_id'] : $pid,
                ];
                //测试储存链接的外部数据库
                //获取储存对应数据库名
                $sqlname = 'chatlog'.$data['cs_id'] % 10;
                $this->users_model->where('openid',$openid)->update(['groupid' => 1]);
                $ret = Db::connect('db_config_chatlog')->name($sqlname)->insert($post_arr);
                // $this->mo_send_type($author_wx['id'],$author_wx['uid']);
                // $ret = Db::name('chatlog')->insert($post_arr);
                if($ret){
                    return $this->buildSuccess(['status'=> 1,'msg'=>'发送成功','send_time'=>time()]);
                }
            }else{
                 return json(['status'=> -1,'error'=>'发送失败']);
            }
    }

    /**
     * 向用户发送媒体消息
     * @param file 媒体资源
     * @param appid 公众号appid
     * @param openid 用户openid
     * @param cs_id 客服id
     * @param type 内容类型
     * @param send_time 发送时间
     * @param customerService 指定客服账号
     */
    public function sendMediaForUser(){
        $data = $this->request->post();
        $file = $this->request->file($data['type']);
        $result = $this->resource($data,$file,$data['type']);
        if($result){
            return $this->buildSuccess($result);
        }else{
            return json(['status'=> -1,'error'=>'发送失败']);
        }
    }

    /**
     * 上传素材资源，返回资源本地路径
     * @param type image[图片] audio[音频]
     */
    private function resource($data,$file,$type){
        // file_put_contents('./requestMsgError.log','['.date("Y-m-d H:i:s").'] appid:'.$data['appid']."\n",FILE_APPEND);
        $appid = $data['appid'];
        $openid = $data['openid'];
        $chat_upload = new Chatupload;
        if($type == 'image'){
            $keyword_arr = $chat_upload->upload($file);
            // $keyword_arr = $file;
        }else if($type == 'voice'){
            $keyword_arr = $chat_upload->voiceUpload($file);
        }
        
        if($keyword_arr['error'] == 0){
            $keyword = $keyword_arr['url'];
        }else{
            return false;
        }
        $customerService = isset($data['customerService']) ? $data['customerService'] : '';
        $author_wx = $this->author_wx_user_model->where('appid',$appid)->where('authorized',1)->find();
        $wechatObj = new WechatThirdUtil($this->config , $author_wx);
        if(!empty($customerService)){
            $chat_resource = $wechatObj->uploadTempMaterial('.'.$keyword,$type);
            $result = $wechatObj->appointSendMediaToOne($openid , $chat_resource['media_id'] ,$type , $customerService);
        }else{
            $chat_resource = $wechatObj->uploadTempMaterial('.'.$keyword,$type);
            $result = $wechatObj->sendMediaToOne($openid , $chat_resource['media_id'] , $type);
        }

        if($result){
            $pid = $this->csuser_model->where('id',$data['cs_id'])->value('pid');
            $post_arr = [
                'type'    => $data['type'],
                'content' => $keyword, //图片路径
                'openid'  => $data['openid'], //用户openid
                'appid'   => $data['appid'], //对应公众号appid
                'cs_id'   => $data['cs_id'], //客服id
                'send_time' => $data['send_time'], //发送时间
                'send_type' => '1002',
                'pid' => $pid == 0 ? $data['cs_id'] : $pid,
            ];

            //获取储存对应数据库名
            $this->users_model->where('openid',$openid)->update(['groupid' => 1]);
            $sqlname = 'chatlog'.$data['cs_id'] % 10;
            $ret = Db::connect('db_config_chatlog')->name($sqlname)->insert($post_arr);
            // $this->mo_send_type($author_wx['id'],$author_wx['uid']);
            // $ret = Db::name('chatlog')->insert($post_arr);
            if($ret){
                return ['status'=> 1,'msg'=>'ok','path'=>$keyword,'send_time'=>time()];
            }
        }else{
            return json_encode(['status'=> -1,'error'=>'send error'],JSON_UNESCAPED_UNICODE);
        }
    }

    /**
     * 从微信api获取用户信息
     * @param appid 公众号appid
     * @param openid 用户openid
     */
    public function getWxUserInfo(){
        $data = $this->request->post();
        $appid = $data['appid'];
        $openid = $data['openid'];
        $author_wx = $this->author_wx_user_model->where('appid',$appid)->where('authorized',1)->find();
        $wechatObj = new WechatThirdUtil($this->config , $author_wx);
        $result = $wechatObj->getFanInfo($openid);
        if($result){
            return $this->buildSuccess(['status' => 1 , 'result' => $result]);
        }else{
            return json_encode(['status'=> -1,'error'=>'error']);
        }
    }

    /**
     * 从数据库获取用户信息
     * @param openid 用户id
     */
    public function getSqlUserInfo(){
        $openid = $this->request->post('openid');
        $result = $this->users_model->alias('u')->where('openid',$openid)->join('think_users_added a','u.user_id = a.uid','LEFT')->find();
        if($result){
            return $this->buildSuccess(['status' => 1 , 'result' => $result]);
        }else{
            return json_encode(['status'=> -1,'error' => 'error']);
        }
        
    }

    /**
     * 获取用户聊天记录，包括需要推送的消息
     * @param openid 用户openid
     * @param cs_id 客服id
     */
    public function getChatLogAll(){
        $data = $this->request->post();
        if($this->csuser_model->where('id',$data['cs_id'])->value('pid') == 0){
            $return = Db::connect('db_config_chatlog')->name('chatlog')->where('pid',$data['cs_id'])->where('openid',$data['openid'])->order('id desc')->select();
        }else{
            $return = Db::connect('db_config_chatlog')->name('chatlog')->where('cs_id',$data['cs_id'])->where('openid',$data['openid'])->order('id desc')->select();
        }

        if($return){
            return $this->buildSuccess(['status' => 1 , 'msg' => '获取成功' , 'chatlog'=>$return]);
        }else{
            return json(['status' => -1, 'error' => '获取用户聊天记录失败']);
        }
    }

    /**
     * 获取聊天记录，包括需要推送的消息
     * @param openid 用户openid
     * @param cs_id 客服id
     * @param offset 偏移量
     * @param last_time 聊天记录last_time
     * @param count 数量
     */
    public function getChatLog(){
        $data = $this->request->post();
        $cs_id = $data['cs_id'];
        $openid = $data['openid'];
        $last_time = isset($data['last_time']) ? $data['last_time'] : '';
        $offset = isset($data['offset']) ? ($data['offset'] < 10 ? $data['offset'] : 10) : 0;
        $count = isset($data['count']) ? ($data['count'] < 10 ? $data['count'] : 10) : 10;
        if($this->csuser_model->where('id',$data['cs_id'])->value('pid') == 0){
            $where = [
                'pid' => ['eq',$cs_id],
                'openid' => ['eq',$openid],
            ];
        }else{
            $where = [
                'cs_id' => ['eq',$cs_id],
                'openid' => ['eq',$openid],
            ];
        }

        if($offset != 0) $count = $offset - $count;
        if(empty($last_time)){
            $result = Db::connect('db_config_chatlog')->name('chatlog')->where($where)->limit($offset,$count)->order('id desc')->select();
        }else{
            $where['send_time'] = ['lt',$last_time];
            $result = Db::connect('db_config_chatlog')->name('chatlog')->where($where)->limit($offset,$count)->order('id desc')->select();
        }

        if($result){
            return $this->buildSuccess(['status' => 1,'chatlog'=>$result]);
        }else{
            return json(['status'=> -1,'error'=>'error','chatlog' => '']);
        }
    }

    /**
     * 获取需要推送的聊天消息
     * @param cs_id 客服id
     */
    public function getPushMsg(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $where = [
                'cs_id' => ['eq' , $data['cs_id']],
                'needsend' => ['eq' , 1],
            ];
            $result = Db::connect('db_config_chatlog')->name('chatlog')->where($where)->order('id desc')->select();
            //获取完聊天记录后把状态改回0
            if($result){
                Db::connect('db_config_chatlog')->name('chatlog')->where($where)->update(['needsend' => 0]);
                return $this->buildSuccess(['status'=>1,'pushmsg'=>$result]);
            }else{
                return json(['status'=> -1,'error'=>'error']);
            }
        }
    }

    /**
     * 已读推送消息，取消推送状态提醒
     * @param openid 用户openid
     * @param cs_id 客服id
     */
    public function clearPushMsg(){
            $data = $this->request->post();
            $where = [
                'cs_id' => ['eq' , $data['cs_id']],
                'openid' => ['eq' , $data['openid']],
                'needsend' => ['eq' , 1],
            ];

            $result = Db::connect('db_config_chatlog')->name('chatlog')->where($where)->update(['needsend' => 0]);
            if($result){
                return $this->buildSuccess(['status'=>1,'msg'=>'状态已清除']);
            }else{
                return json_encode(['status'=> -1,'error'=>'状态清除失败']);
            }
    }

    /**
     * 给用户打标签
     * @param type appid
     * @param type tagid
     * @param type openid
     */
    public function setUserTags(){
        $data = $this->request->post();
        $appid = $data['appid'];
        // $openid_list[] = $data['openid'];
        $openid = $data['openid'];
        $tagid = $data['tagid'];
        $author_wx = $this->author_wx_user_model->where('appid',$appid)->where('authorized',1)->find();
        $wechatObj = new WechatThirdUtil($this->config , $author_wx);
        $result = $wechatObj->batchUsersTag([$openid],$tagid);
        if($result){
            $tagid_list = $this->users_model->where('openid',$openid)->value('tagid_list');
            $tagid_list_arr = unserialize($tagid_list);
            $tagid_list_arr[] = $tagid;
            $tagid_list_arr = array_unique($tagid_list_arr);
            // $res = M('users')->where('openid','IN',implode(',',$openid_list))->update(['tagid_list'=>serialize($tagid_list_arr)]);
            $res = $this->users_model->where('openid',$openid)->update(['tagid_list'=>serialize($tagid_list_arr)]);
            if(!$res){
                return json(['status' => -1,'error' => 'Update user taglist error']);
            }else{
                return $this->buildSuccess(['status' => 1,'msg' => 'ok' , 'tagid_list' => $tagid_list_arr]);
            }
        }else{
            return json(['status' => -1,'msg' => 'Save tag to WeChat failure']);
        }
    }

    /**
     * 给用户删除标签
     * @param type appid
     * @param type tagid
     * @param type openid
     */
    public function delUserTags(){
        $data = $this->request->post();
        $appid = $data['appid'];
        $openid = $data['openid'];
        $tagid = $data['tagid'];
        $author_wx = $this->author_wx_user_model->where('appid',$appid)->where('authorized',1)->find();
        $wechatObj = new WechatThirdUtil($this->config , $author_wx);
        $result = $wechatObj->batchCancelUsersTag([$openid],$tagid);
        if($result){
            $tagid_list = $this->users_model->where('openid',$openid)->value('tagid_list');
            $tagid_list_arr = unserialize($tagid_list);
            $filp_tagid_list_arr = array_flip($tagid_list_arr); //调换键值
            if(array_key_exists($tagid,$filp_tagid_list_arr)){
                unset($filp_tagid_list_arr[$tagid]);
                $tagid_list_arr = array_flip($filp_tagid_list_arr);
                $res = $this->users_model->where('openid',$openid)->update(['tagid_list'=>serialize($tagid_list_arr)]);
                // $res = M('users')->where('openid','IN',implode(',',$openid_list))->update(['tagid_list'=>serialize($tagid_list_arr)]);
                if($res){
                    return $this->buildSuccess(['status'=>1,'msg'=>'删除成功','tagid_list' => $tagid_list_arr]);
                }else{
                    // echo M('users')->getLastSql();
                    return json(['status'=>-1,'error'=>'Update user taglist error']);
                }
            }
        }else{
            return json(['status'=>-1,'msg'=>'Save tag to WeChat failure']);
        }
    }

    /**
     * 自动推送前15个用户信息
     * @param type cs_id 
     */
    public function autoPushMsg(){
        $cs_id = $this->request->post('cs_id');
        if($this->csuser_model->where('id',$cs_id)->value('pid') == 0){
            $map = [
                'pid' => ['eq',$cs_id],
            ];
        }else{
            $map = [
                'cs_id' => ['eq',$cs_id],
            ];
        }

        $where = [
            'butt_id' => ['eq',$cs_id],
            'subscribe' => ['eq',1],
        ];

        //获取聊天时间最晚的
        $openids = Db::connect('db_config_chatlog')->name('chatlog')->where($map)->group('openid')->order('send_time desc')->limit(50)->column('openid');
        if($openids != true) return json(['status' => -1, 'error'=> 'openids is empty' ]);
        $result = $this->users_model->field('user_id,sex,openid,headimgurl,nickname,wechat_num,name,phone,age')->alias('u')->whereIn('openid',$openids)->where('subscribe',1)
                    ->union("SELECT user_id,sex,openid,headimgurl,nickname,wechat_num,name,phone,age FROM think_users as s LEFT JOIN think_users_added as d ON s.user_id = d.uid WHERE butt_id = {$cs_id} AND subscribe = 1 LIMIT 50")
                    ->join('think_users_added a','u.user_id = a.uid','LEFT')
                    ->select();
        
        //获取最晚关注的
        // $result = $this->users_model->alias('u')->where($where)
        //             ->join('think_users_added a','u.user_id = a.uid','LEFT')
        //             ->order('subscribe_time desc')->limit(15)->select();
        if($result){
            foreach($result as $v){
                $chatlog = Db::connect('db_config_chatlog')->name('chatlog')->where('openid',$v['openid'])->order('send_time DESC')->limit(10)->select();
                $v['chatlog'] = array_reverse($chatlog);
            }
            return $this->buildSuccess(['status' => 1, 'msg'=> '获取成功' , 'result' => $result]);
        }else{
            return json(['status' => -1, 'error'=> 'maybe query error,please check' ]);
        }
    }

    /**
     * 获取公众号openid
     * @param id 公众号id
     */
    public function getOpenidAll(){
        if($this->request->isPost()){
            $id = $this->request->post('id');
            $where = [
                'subscribe' => ['eq',1],
                'auid' => ['eq',$id],
            ];
            $openid = $this->users_model->where('auid',$id)->column('openid');
            if($openid) return $this->buildSuccess(['status' => 1 ,'msg' => '获取成功' , 'openids' => $openid]);
            return json(['status' => -1 ,'error' => 'not find openid']);
        }
    }
}